import simplejson
import traceback
import logging
from django.http import HttpResponse
from django.contrib.csrf.middleware import csrf_exempt

from lyricsplit.models import LyricLine,LyricLrc,EmoAnno,EmoAnnoOk

@csrf_exempt
def ajax_anno_line(request):
    try:
        # get the lyric
        k = request.POST['llkey']
        anno = request.POST['anno']

        ll = LyricLine.get(k)
        ll.split_anno = anno
        ll.put()

        # should update the anno_dt automatically
        return HttpResponse(
                simplejson.dumps({'code':0}))
    except Exception,e:
        return HttpResponse(simplejson.dumps({
            'code':1,
            'data':{
                'errorMessage':traceback.format_exc()
                }}))


@csrf_exempt
def import_split(request):
    """
    return the key of the lyriclrc
    """
    try:
        name = request.POST['name']
        lrcstr = request.POST['lrcstr']

        # check the format
        # store each line
        from LyricStructure.pylyric.Lyric import Lyric
        
        logging.error(lrcstr)

        l = Lyric()
        l.loadstr(lrcstr)
        ldiclist = l.getlinelist()
        
        # store the lrc
        ll = LyricLrc()
        tmp_lrcstr = lrcstr[:]
        tmp_lrcstr = tmp_lrcstr.replace(" ","")
        ll.lrc_str = tmp_lrcstr
        ll.hot_num = 0
        ll.name = name
        ll.put()

        eao = EmoAnnoOk()
        eao.lrc = ll
        eao.anno_ok = 0
        eao.put()

        """
        for ldic in ldiclist:
            lline = LyricLine()
            lline.time = float(ldic['time'])
            tmp_line = ldic['content'][:]
            lline.split_anno =  tmp_line
            lline.line = tmp_line.replace(" ","")
            lline.lrc = ll
            lline.put()
        """

        return HttpResponse(simplejson.dumps({
            'code':0,
            'data':{
                'key':str(ll.key())
                }
            }))
    except:
        return HttpResponse(simplejson.dumps({
            'code':1,
            'data':{
                'errorMessage':traceback.format_exc()
                }}))


@csrf_exempt
def ajax_anno_emo(request):
    try:
        l_key = request.POST['l_key']
        emo = request.POST['emo']
        desc = request.POST['desc']
        anno_ip = request.META['REMOTE_ADDR']

        # store this
        emoanno = EmoAnno()
        emoanno.lrc = LyricLrc.get(l_key)
        emoanno.emo = emo
        emoanno.anno_desc = desc
        emoanno.anno_ip = anno_ip
        emoanno.put()

        #EmoAnnoOk.
        #if EmoAnnoOk.all().filter(""
        eao = EmoAnnoOk.all().filter( "lrc =",LyricLrc.get(l_key) )[0]
        eao.anno_ok = 1
        eao.put()

        return HttpResponse(simplejson.dumps({
            'code':0}))

    except:
        return HttpResponse(simplejson.dumps({
            'code':1,
            'data':{
                'errorMessage':traceback.format_exc()
                }}))

